package data_structure.linkedList;

/**
 * @ClassName : data_structure.linkedList.DoubleLinkedList
 * @Description : 类描述
 * Created by cyd on 2021-01-27 23:08:40
 */
public class DoubleLinkedList {
    private HeroNode2 head = new HeroNode2(0, "头节点", "头节点");

    // 添加节点的方法，仅用于添加元首节点
    private void add(HeroNode2 node) {
        // 1.找到当前链表的最后一个节点
        // 2.将最后一个节点的next（数据域）指向新的节点
        HeroNode2 temp = head;
        while (temp.getNext() != null) {
            // 如果找到了最后一个节点，就终止循环，此时temp是最后一个节点
            // 每找到一个节点，就将temp后移一位
            temp = temp.getNext();
        }
        temp.setNext(node);
        node.setPre(temp);
    }

    // 判断链表为空的方法
    public boolean isEmpty() {
        return head.getNext() == null;
    }

    // 展示链表
    public void show() {
        if (this.isEmpty()) return;

        HeroNode2 temp = head;
        System.out.println(temp);
        while (temp.getNext() != null) {
            System.out.println(temp.getNext());
            temp = temp.getNext();
        }
    }

    // 根据索引找到节点
    public HeroNode2 selectByIndex(Integer index) {
        HeroNode2 temp = head;
        while (head.getNext() != null) {
            if (index.equals(temp.getNo())) return temp;
            temp = temp.getNext();
        }

        return null;
    }

    // 按照索引删除元素
    public void deleteNode(Integer index) {
        if (this.isEmpty()) return;
        if (this.selectByIndex(index) == null) return;
        HeroNode2 currentNode = this.selectByIndex(index);
        HeroNode2 nextNode = currentNode.getNext();
        HeroNode2 preNode = currentNode.getPre();
        nextNode.setPre(preNode);
        preNode.setNext(nextNode);
    }

    public static void main(String[] args) {
        DoubleLinkedList doubleLinkedList = new DoubleLinkedList();
        doubleLinkedList.add(new HeroNode2(1, "songjiang", "jishiyu"));
        doubleLinkedList.add(new HeroNode2(2, "heixuanfeng", "likui"));
        doubleLinkedList.add(new HeroNode2(3, "linchong", "baozitou"));
        doubleLinkedList.show();
        System.out.println("--------------删除索引为2的元素------------------");
        doubleLinkedList.deleteNode(2);
        doubleLinkedList.show();
    }
}
